package com.neo.handlers;

import com.google.common.base.Splitter;
import com.neo.domain.Address;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.assertj.core.util.Strings;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: hredis
 * @Date: 2020/10/25 23:52
 */

@MappedTypes(value = Address.class)   /* 转化后的数据类型 */
public class AddressTypeHandler extends BaseTypeHandler<Address> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Address parameter, JdbcType jdbcType) throws SQLException {
        if(parameter == null) {
            return;
        }
        String addressString = Strings.join(parameter.getProvince(), parameter.getCity(), parameter.getStreet()).with(",");
        ps.setString(i, addressString);
    }

    @Override
    public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        return getAddress(columnValue);
    }

    /**
     *  字符串转为对象  A,B,C -> 对象
     * @param columnValue   类似A,B,C
     * @return  对象
     */
    private Address getAddress(String columnValue) {
        if (columnValue == null || columnValue.equals("") || !columnValue.contains(",")) {
            return null;
        }
        List<String> aList = Splitter.on(",").splitToList(columnValue);
        return new Address(aList.get(0), aList.get(1), aList.get(2));
    }

    @Override
    public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return getAddress(columnValue);
    }

    @Override
    public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return getAddress(columnValue);
    }
}
